/**
 * 
 */
package com.zznode.client.wlanpolling.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

/**
 * @author Jerome
 * 
 */
public class PingTask extends AsyncTask<String, String, String> {

	// 命令行更新，延时更新，丢包率更新
	private IMessageUpdater[] msgUpdaters = null;
	private ProgressDialog pd = null;
	private Process p = null;

	public PingTask(IMessageUpdater[] msgUpdaters, ProgressDialog pd) {
		super();
		this.msgUpdaters = msgUpdaters;
		this.pd = pd;
	}
	
	// 命令行更新，延时更新，丢包率更新，丢包数，最小时延，最大时延
	public PingTask(IMessageUpdater[] msgUpdaters) {
		super();
		this.msgUpdaters = msgUpdaters;
	}

	@Override
	protected String doInBackground(String... params) {
		String s = null;
		String s1 = params[1];
		if (s1.contains(".") && s1.length() > 3) {
			try {
				String s2 = params[0];
				if (s2 != null) {
					//TODO 需要从配置中获取参数
					ping((new StringBuilder("ping ")).append(s2).append(" ")
							.append(s1).toString());
				}
			} catch (Exception exception) {
				Log.e("Ping",
						(new StringBuilder("Error: ")).append(
								exception.getMessage()).toString());
				s = (new StringBuilder("Error: ")).append(
						exception.getMessage()).toString();
			}
		} else {
			Log.e("Ping", "Error: Invalid network address");
			s = "Error: Invalid network address";
		}
		
		return s;
	}

	@Override
	protected void onPostExecute(String result) {
		if (pd != null) {
			pd.dismiss();
		}
		
		if (result != null) {
			Toast.makeText(getContext(), result, Toast.LENGTH_LONG).show();
		}
	}

	@Override
	protected void onProgressUpdate(String... values) {
		if (values != null && values.length >= 3) {
			for (int i = 0; i < values.length; i++) {
				if (msgUpdaters[i] != null) {
					msgUpdaters[i].messageUpdated(values[i]);
				}
			}
		}
	}

	private void ping(String s) {
		try {
			p = Runtime.getRuntime().exec(s);
			BufferedReader bufferedreader = new BufferedReader(
					new InputStreamReader(p.getInputStream()), 8192);
			
			String as[] = new String[msgUpdaters.length];
			for(int i = 0; i < as.length; i++){
				as[i] = "";
			}
			
			do {
				String s1 = bufferedreader.readLine();
				if (s1 == null) {
					bufferedreader.close();
					p.destroy();
					break;
				}
				fillStatistics(s1, as);
				publishProgress(as);
				try {
					Thread.sleep(150);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} while (!isCancelled());
		} catch (IOException ioexception) {
			ioexception.printStackTrace();
		}
	}
	
	private void fillStatistics(String s1, String[] as){
		as[0] = s1;
		String keyLost = "received, ";
		String keyDelay = "rtt min/avg/max/mdev = ";
		int index = s1.indexOf(keyLost);
		if (index != -1) {
			if (as.length > 3) {
				String transmitted = s1.substring(0, s1.indexOf(" "));
				int firstIndex = s1.indexOf(", ");
				int lastIndex = s1.indexOf(" ", firstIndex + 3);
				String received = s1.substring(firstIndex + 2, lastIndex);
				as[3] = (Integer.parseInt(transmitted) - Integer
						.parseInt(received)) + "";
			}
			int sIndex = s1.indexOf("%", index);
			as[2] = s1.substring(index + keyLost.length(), sIndex);
		}
		index = s1.indexOf(keyDelay);
		int sIndex = -1, nextIndex = -1;
		if (index != -1) {
			sIndex = s1.indexOf("/", index + keyDelay.length());
			nextIndex = s1.indexOf("/", sIndex + 1);
			as[1] = s1.substring(sIndex + 1, nextIndex);
		}		
		if(index != -1 && sIndex != -1 && nextIndex != -1 && as.length > 3){
			as[4] = s1.substring(index + keyDelay.length(), sIndex);
			sIndex = s1.indexOf("/", sIndex + 1);
			nextIndex = s1.indexOf("/", sIndex + 1);
			as[5] = s1.substring(sIndex + 1, nextIndex);
		}
	}

	private Context getContext() {
		if (msgUpdaters != null) {
			for (int i = 0; i < msgUpdaters.length; i++) {
				if (msgUpdaters[i] != null)
					return msgUpdaters[i].getContext();
			}
		}
		
		return null;
	}

}
